package org.openspml.providers.one_c.commands;

import org.openspml.message.AddRequest;
import org.openspml.message.SpmlResponse;
import org.openspml.providers.one_c.api.connection.GlobalContext;
import org.openspml.providers.one_c.api.users.InfoBaseUser;
import org.openspml.providers.one_c.api.users.InfoBaseUsersManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Command for creating new user.
 * 
 * @author <A href="mailto:abashev at gmail dot com">Alexey Abashev</A>
 * @version $Id$
 */
public class AddRequestCommand {
	public static final String FIRST_NAME = "gn";
	public static final String LAST_NAME = "sn";
	public static final String PASSWORD = "password";
	
	private final Logger log = LoggerFactory.getLogger(AddRequestCommand.class);

	public SpmlResponse execute(GlobalContext context, AddRequest request) {
		SpmlResponse response = request.createResponse();

		final String id = request.getIdentifierString();
		final String objectClass = request.getObjectClass();
		
		if (!objectClass.equals("person")) {
			String message = "Unsupported object class [" + objectClass + "]";

			log.warn(message);
			
	        response.setError(SpmlResponse.ERROR_UNSUPPORTED_IDENTIFIER_TYPE);
	        response.setErrorMessage(message);
	        
	        return response;
		}
		
		try {
			InfoBaseUsersManager manager = context.getInfoBaseUsers();
			
			if (manager.findByName(id) != null) {
				log.warn("Already has user [id={}]", id);
				
				response.setResult(SpmlResponse.RESULT_FAILURE);
				response.setErrorMessage("User with id [" + id + "] already exist");
				
				return response;
			}
			
			log.trace("Start creating new user [id={}]", id);
			
			InfoBaseUser newUser = manager.createUser();

			final String fullName = request.getAttribute(FIRST_NAME).getValue() + " " + request.getAttribute(LAST_NAME).getValue();
			
			newUser.setName(id);
			
			log.trace("[full name = {}]", fullName);
			
			newUser.setFullName(fullName);
			newUser.setPassword((String) request.getAttribute(PASSWORD).getValue());
			
			// Setting default values
			newUser.setStandardAuthentication(true);
			newUser.setCanChangePassword(false);
			newUser.setShowInList(true);
			newUser.clearRoles();
			
			log.trace("Writing user [{}] into database", id);

			newUser.write();

			response.setResult(SpmlResponse.RESULT_SUCCESS);
		} catch (Exception e) {
			log.error("Unable to create user [" + id + "]", e);
			
	        response.setError(SpmlResponse.ERROR_CUSTOM_ERROR);
	        response.setErrorMessage(e);
		}
		
		return response;
	}
}
